﻿/**************************************************************************
创建日期:	2019/7/19 15:07:48     
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com
创建时间:	
Copyright (c)  ZhCun.cn

描	述：
记	录：
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using ZhCun.DbCore.BuildSQLText;
using ZhCun.DBModel;
using ZhCun.WebUtils.VModel;

namespace ZhCun.WebUtils.DB
{
    public class HomeBaseBLL : BLLBase
    {
        /// <summary>
        /// 获取主页实体对象，菜单列表，
        /// </summary>
        public VM_HomeIndex GetHomeModel()
        {
            VM_HomeIndex vm = new VM_HomeIndex();
            vm.Menus = GetViewMenu();
            return vm;
        }

        protected virtual void SetQueryMenuWhere(ISqlBuilder sql)
        {
            sql.AddSQLText(" and IsSystem = 1");
        }

        /// <summary>
        /// 得到视图菜单
        /// </summary>
        public virtual List<VM_HomeMenu> GetViewMenu()
        {
            var sqlWhere = DB.CreateSqlBuilder();
            sqlWhere.AddSQLText("IsEnable = 1 and IsApi = 0");
            SetQueryMenuWhere(sqlWhere);
            sqlWhere.AddSQLText(" order by MenuLevel,OrderNo");
            var menuList = DB.Query<Sys_Menu>(sqlWhere).ToList(true);

            List<VM_HomeMenu> rMenus = new List<VM_HomeMenu>();
            foreach (var item in menuList)
            {
                if (string.IsNullOrWhiteSpace(item.PId))
                {
                    VM_HomeMenu m = ToViewMenu(item);
                    LoadSubMenus(m, menuList);
                    rMenus.Add(m);
                }
            }
            return rMenus;
        }

        protected void LoadSubMenus(VM_HomeMenu pMenu, List<Sys_Menu> menuList)
        {
            foreach (var item in menuList)
            {
                if (item.PId == pMenu.MenuId)
                {
                    VM_HomeMenu m = ToViewMenu(item);
                    LoadSubMenus(m, menuList);
                    pMenu.SubMenus.Add(m);
                }
            }
        }

        protected VM_HomeMenu ToViewMenu(Sys_Menu menu)
        {
            VM_HomeMenu m = new VM_HomeMenu();
            m.MenuId = menu.Id;
            m.IsExpand = menu.IsExpand;
            m.MenuIcon = menu.MenuIcon;
            m.MenuName = menu.MenuName;
            m.MenuUrl = menu.MenuUrl;
            m.SubMenus = new List<VM_HomeMenu>();
            return m;
        }
    }
}